/* eslint-disable no-undef */
import React from "react";
import { Button, message, Modal, Form, Input, Spin } from "antd";
import { messages } from "share/common";
import "styles/scan-wrap/index.scss";
import { connect } from "react-redux";
import mainService from "containers/main.service";
import menuRoute from "routes/menuRoute";
import canonScanService from "components/canon-scan/canon-scan-service";
import configureStore from "stores/index";
// 佳能扫描仪连接
class CanonScan extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      disabled: true,
      isScan: false,
    };
    this.connector = null;
    this.uniqueKey = null;
  }

  componentDidMount() {
    console.log("佳能扫描仪。。。。。。。")
    this.initScanStatus(this.props.enableScan);
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.enableScan !== this.props.enableScan) {
      this.initScanStatus(nextProps.enableScan);
    }
  }
  componentWillUnmount = () => {
    // 关闭卷票机连接
    if (this.connector) {
      this.connector.close();
      this.uniqueKey = null;
    }
  };
  initScanStatus = (enableScan) => {
    if (enableScan === "CANON") {
      this.setState({ disabled: false });
    }
    // 新版卷票机 需要和后端建立长连接
    if (enableScan === "CANON_V2") {
      this.initConnector();
    }
  };
  initConnector = () => {
    this.connector = canonScanService.initWebSocket({
      onOpen: () => {
        let params = {
          command: "CONNECT",
        };
        if (this.uniqueKey) {
          params.uniqueKey = this.uniqueKey;
        }
        let dataSend = JSON.stringify(params) + "\0";
        this.connector.send(dataSend);
      },
      onMessage: this.onMessage,
      onerror: () => {
        // 关闭卷票机连接
        if (this.connector) {
          console.log("是否关闭卷票机连接。。。。。。")
          this.connector.close();
          this.uniqueKey = null;
          this.setState({ disabled: true });
        }
      },
    });
  };
  onMessage = (res) => {
    let result = JSON.parse(res.data.replace("\0", ""));
    if (result.msgType === "CONNECT" && !this.uniqueKey) {
      this.uniqueKey = result.uniqueKey;
      this.setState({ disabled: false });
    } else if (result.msgType === "scan") {
      // 扫描结束
      if (result.msgContent === "close") {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.setState({ isScan: false });
      } else if (result.file) {
        this.resetTimer();
        this.props.onScan({
          imageData: result.file,
        });
      }
    }
  };
  openInvoiceInfoAuthority() {
    window.open(`${window.ISIE9 ? "#" : ""}${menuRoute.getRouteItem("invoice-source-check").url}`, "_blank");
  }
  getOpenInvoiceInfoAuthority = () => {
    return mainService.checkMenuAuth(menuRoute.getRouteItem("invoice-source-check", "key"));
  };
  getShowExpenseExtra(str, linkBtn, specialStr) {
    let showExtra = str.split(specialStr);
    return (
      <div>
        {showExtra[0]}
        {linkBtn}
        {showExtra[1]}
      </div>
    );
  }
  // 新版驱动取消无法获取到信息 所以添加一个计时器 若10s没有反应 则关闭弹窗
  // 若有反应也重新设置计时器
  resetTimer = () => {
    if (this.timer) {
      clearTimeout(this.timer);
    }
    console.log("是否是新驱动的原因。。。。。。。。。")
    this.timer = setTimeout(() => {
      this.setState({ isScan: false });
    }, 10000);
  };
  capture = () => {
    const { isScan } = this.state;
    if (!this.props.showOCRFlag) {
      let replaceInfo = messages("common-1.key1236"); /*发票来源与查验*/
      let linkBtn = <a onClick={() => this.openInvoiceInfoAuthority()}>{replaceInfo}</a>;
      let infoMessage = messages("common-1.key1237", {
        arg1: replaceInfo,
      }); /*请管理员在{arg1}菜单，开通发票识别服务*/
      let openInvoiceAuthority = this.getOpenInvoiceInfoAuthority();
      Modal.info({
        title: messages("common-1.key71") /*说明*/,
        content: openInvoiceAuthority ? this.getShowExpenseExtra(infoMessage, linkBtn, replaceInfo) : infoMessage,
      });
      this.props.onEventTrack({ notOCRFlag: true });
      return !1;
    }
    if (this.state.disabled) {
      const labels = [
        messages(
          "common-1.key1238"
        ) /*1. 扫描仪已和电脑保持连接，并且扫描仪处于开机状态（扫描仪型号要求：佳能DR-M1060、佳能DR-M140、富士通IX1500L、富士通IX500）*/,
        messages(
          "common-1.key1239"
        ) /*2. 驱动安装完毕，并且在任务管理器- 进程中为启动状态。各型号对应进程名称：佳能 ScanServer 、富士通 PfuSsService*/,
      ];
      Modal.info({
        title: messages("common-1.key1240") /*请确保已完成以下操作*/,
        content: (
          <section>
            {labels.map((item) => (
              <p>{item}</p>
            ))}
          </section>
        ),
      });
      this.props.onEventTrack({ disabled: true });
      return !1;
    }
    if (isScan) {
      return !1;
    }
    this.props.onStartScan();
    this.setState({ isScan: true });
    console.log('1111111,是不是这里，这里已经是true了')
    if (this.props.enableScan === "CANON_V2") {
      this.resetTimer();
      canonScanService.startScan({
        type: "scan",
        key: this.uniqueKey,
        authorization: `BearerSPACE${configureStore.store.getState().main.authToken.access_token}`,
      });
      return !1;
    }
    let testSaveFolder = `${location.origin}/api/upload/attachment`;
    let token = this.props.authToken.access_token;
    imageFORMULAScanJS
      .scan(testSaveFolder, token)
      .then((res) => {
        if (res.result == "true") {
          if (res.value && res.value.files && res.value.files.length > 0) {
            let files = res.value.files;
            files.forEach((file) => {
              if (file.uploadstatuscode === 200) {
                this.props.onScan({
                  attachmentDTO: JSON.parse(file.uploadresponsetext),
                });
              }
            });
          }
        }
      })
      .catch((error) => {
        this.setState({ isScan: false });
        try {
          if (["-4426", "-4401"].includes(error.value.internal_code)) {
            // -4426 卡纸
            // -4401 没有纸
            return !1;
          }
        } catch (e) {}
        let currentScanServer = "ScanServer";
        const labels = [
          messages("common-1.key1241", {
            arg1: currentScanServer,
          }) /*1. 请在任务管理器- 进程中重启名为{arg1}的驱动*/,
          messages("common-1.key1242") /*2. 重启驱动后请刷新浏览器*/,
          messages("common-1.key1297") /*3. 如仍有问题，请联系扫描设备的技术支持：4008205226 或 151 9048 9653*/,
        ];
        Modal.info({
          title: messages("common-1.key1240") /*请确保已完成以下操作*/,
          content: (
            <section>
              {labels.map((item) => (
                <p>{item}</p>
              ))}
            </section>
          ),
        });
        this.props.onEventTrack({
          errorInfo: `${error.function}-${error.value}-${error.imageFORMULAWebScanSDK}`,
        });
      })
      .finally(() => {
        this.setState({ isScan: false });
      });
  };

  render() {
    const { isScan, disabled } = this.state;
    const { text, buttonProps } = this.props;
    let wrapButtonProps = { ...buttonProps };
    wrapButtonProps.loading = !!buttonProps.loading || isScan;
    if (disabled) {
      wrapButtonProps.type = "default";
    }
    return (
      <Button onClick={this.capture} {...wrapButtonProps}>
        {text || messages("common-1.key31") /*扫描*/}
      </Button>
    );
  }
}

CanonScan.propTypes = {
  onScan: React.PropTypes.func,
  onStartScan: React.PropTypes.func,
  onEventTrack: React.PropTypes.func,
  buttonProps: React.PropTypes.object,
  text: React.PropTypes.string,
};
function mapStateToProps(state) {
  return {
    authToken: state.main.authToken,
    enableScan: state.main.enableScan,
  };
}

export default connect(mapStateToProps)(CanonScan);
